package com.stedu.mall.userservice.controller;

import com.github.pagehelper.PageInfo;
import com.stedu.mall.common.bean.Collect;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.CollectService;
import com.stedu.mall.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/collect")
public class CollectController {
    @Autowired
    private CollectService collectService;

    //添加
    @PostMapping("/{goodsId}")
    public RespBean insert(@PathVariable("goodsId") Integer goodsId, @RequestHeader("token") String token) throws SteduException {
        //不需要获取jwt,直接解析
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        //获取用户id
        Integer id = (Integer) map.get("id");
        //设置收藏对象
        Collect collect = new Collect();
        collect.setGoodsId(goodsId);
        collect.setUserId(id);
        //添加
        collectService.insert(collect);
        return RespBean.ok("收藏成功");
    }

    // 删除
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id, @RequestHeader("token") String token) throws SteduException {
        //不需要获取jwt,直接解析
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        //获取用户id
        Integer userId = (Integer) map.get("id");
        collectService.delete(id, userId);
        return RespBean.ok("删除成功");
    }

    //根据商品id与用户id查询
    @GetMapping("/{goodsId}")
    public RespBean selectByGoodsIdAndUserid(@PathVariable("goodsId") Integer goodsId, @RequestHeader("token") String token) {
        //不需要获取jwt,直接解析
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        //获取用户id
        Integer userId = (Integer) map.get("id");
        Collect collect = collectService.selectByGoodsIdAndUserId(goodsId, userId);
        return RespBean.ok("查询成功", collect);
    }

    //根据id查询
    //@GetMapping("/{id}")
    //public RespBean selectById(@PathVariable("id") Integer id) {
    //    return RespBean.ok("", collectService.selectById(id));
    //}

    //分页查询
    @GetMapping
    public RespBean selectByPage(@RequestHeader("token") String token, Integer pageNum, Integer pageSize) {
        //不需要获取jwt,直接解析
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        //获取用户id
        Integer userId = (Integer) map.get("id");
        //前端可能没传过来pageNum,pageSize
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 5 : pageSize;
        PageInfo<Collect> data = collectService.selectByPage(pageNum, pageSize, userId);
        return RespBean.ok("", data);
    }
}
